package tio.study.showcase.client;

import org.tio.client.*;
import org.tio.client.intf.TioClientHandler;
import org.tio.client.intf.TioClientListener;
import org.tio.core.Node;
import org.tio.core.Tio;
import org.tio.utils.json.Json;
import tio.study.showcase.common.Const;
import tio.study.showcase.common.ShowcasePacket;
import tio.study.showcase.common.Type;
import tio.study.showcase.common.packets.GroupMsgReqBody;

/**
 * @author tanyaowu
 */
public class GroupMsgClientStarter {
    static String serverIp = "127.0.0.1";
    static int serverPort = Const.PORT;

    private static Node serverNode = new Node(serverIp, serverPort);

    /**
     * 用来自动连接的，不想自动连接请设为null
     */
    private static ReconnConf reconnConf = new ReconnConf(5000L);

    private static TioClientHandler tioClientHandler = new ShowcaseClientTioHandler();

    private static TioClientListener tioClientListener = new ShowcaseClientTioListener();
    /**
     * 一组连接共用的上下文对象
     */
    public static TioClientConfig tioClientConfig = new TioClientConfig(tioClientHandler, tioClientListener, reconnConf);

    private static TioClient tioClient = null;

    static ClientChannelContext clientChannelContext;

    public static void main(String[] args) throws Exception {
        tioClient = new TioClient(tioClientConfig);
        clientChannelContext = tioClient.connect(serverNode);
        command();
    }

    public static void command() throws Exception {
        String group = "group1";
        String text = "你好";
        processCommand(group, text);
        tioClient.stop();
        System.exit(0);
    }

    public static void processCommand(String group, String text) throws Exception {
        GroupMsgReqBody groupMsgReqBody = new GroupMsgReqBody();
        groupMsgReqBody.setToGroup(group);
        groupMsgReqBody.setText(text);

        ShowcasePacket reqPacket = new ShowcasePacket();
        reqPacket.setType(Type.GROUP_MSG_REQ);
        reqPacket.setBody(Json.toJson(groupMsgReqBody).getBytes(ShowcasePacket.CHARSET));

        Tio.send(clientChannelContext, reqPacket);
    }
}
